#!/usr/bin/env python
# -*- encoding:utf8 -*-

""" 天文时钟 """

import ephem
import arrow
from flask import Flask, request, jsonify
from calc import get_sidereal_time, calc_hour_angle

app = Flask(__name__)


@app.route("/")
def index():
    return "太阳系天体时刻表"


@app.route("/hour-angle", methods={'GET'})
def polaris_hour():
    lat = request.args.get('lat')
    lon = request.args.get('lon')
    elev = request.args.get('elev')

    data = {"北极星时角": calc_hour_angle(get_sidereal_time(lat, lon, elev))}

    return jsonify(data)


@app.route("/api", methods={'GET'})
def api():
    city = ephem.Observer()
    city.lat = request.args.get('lat')
    city.lon = request.args.get('lon')
    city.date = str(request.args.get('date'))
    city.elev = float(request.args.get('elev'))

    sun = ephem.Sun()
    moon = ephem.Moon()
    venus = ephem.Venus()
    jupiter = ephem.Jupiter()
    mercury = ephem.Mercury()
    mars = ephem.Mars()
    saturn = ephem.Saturn()
    uranus = ephem.Uranus()
    neptune = ephem.Neptune()

    data = {'太阳': compute(city, sun),
            '月亮': compute(city, moon),
            '金星': compute(city, venus),
            '木星': compute(city, jupiter),
            '水星': compute(city, mercury),
            '火星': compute(city, mars),
            '土星': compute(city, saturn),
            '天王星': compute(city, uranus),
            '海王星': compute(city, neptune)}
    return jsonify(data)


def compute(city, target):
    time_zone = 'Asia/Shanghai'
    day = str(arrow.get(city.date.datetime()).format('YYYY-MM-DD'))
    # 计算当天升起时间
    previous_rising = str(arrow.get(city.previous_rising(target).datetime()).to(time_zone))
    if previous_rising.find(day) != -1:
        rising_time = previous_rising
    else:
        rising_time = str(arrow.get(city.next_rising(target).datetime()).to(time_zone))

    # 计算当天中天时间
    previous_transit = str(arrow.get(city.previous_transit(target).datetime()).to(time_zone))
    if previous_transit.find(day) != -1:
        transit_time = previous_transit
    else:
        transit_time = str(arrow.get(city.next_transit(target).datetime()).to(time_zone))
    # 计算当天下降时间
    previous_setting = str(arrow.get(city.previous_setting(target).datetime()).to(time_zone))
    if previous_setting.find(day) != -1:
        setting_time = previous_setting
    else:
        setting_time = str(arrow.get(city.next_setting(target).datetime()).to(time_zone))
    return {'升起': rising_time, '中天': transit_time, '降落': setting_time}


if __name__ == '__main__':
    app.run()
